package com.dcy.db.handler;

import cn.hutool.core.exceptions.ValidateException;
import com.dcy.common.model.R;
import com.dcy.common.model.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * @Author：dcy
 * @Description: 全局的的异常拦截器
 * @Date: 2021/4/15 15:39
 */
@RestControllerAdvice
@Order(-1)
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 校验异常
     *
     * @param validException
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ValidateException.class)
    public R<String> validExceptionHandler(ValidateException validException) {
        log.warn("validExceptionHandler [{}]", validException.toString());
//        validException.printStackTrace();
        return R.error(ReturnCode.TOKEN_ERROR.getCode(), validException.getMessage());
    }

    /**
     * 基本数据类型，验证错误
     *
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ValidationException.class)
    public R<String> validationExceptionHandler(ValidationException exception) {
        log.warn("validationExceptionHandle [{}]", exception.toString());
//        exception.printStackTrace();
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                return R.error(ReturnCode.CHECK_ERROR.getCode(), item.getMessage());
            }
        }
        return R.error(ReturnCode.CHECK_ERROR.getCode(), exception.getMessage());
    }

    /**
     * 所有异常信息
     *
     * @param exception
     * @return
     * @throws Exception
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception exception) {
        log.error("exceptionHandle [{}]", exception.toString());
        exception.printStackTrace();
        return R.error(ReturnCode.OTHER_ERROR.getCode(), exception.getMessage());
    }

}
